package service

import (
	"shop/config/constant"
	"shop/dao"
	"shop/utils/convertutil"
	"shop/utils/genutil"
	"shop/utils/result"
	"shop/utils/tcentcloudutil"
	"strconv"
	"time"
)

// SendPhoneVerifyCode 发送手机验证码, ttl:多少秒后过期，maxLimit:一天最多可以发送多少次
func SendPhoneVerifyCode(phone, keyPrefix string, ttl int64, maxLimit int) *result.Result {
	key := keyPrefix + phone
	remainSeconds := int64(dao.GetRedisCli().TTL(key).Val().Seconds())
	if remainSeconds > 0 {
		return result.Ok(remainSeconds).SetMsg("验证码已发送，" + strconv.FormatInt(remainSeconds, 10) + "秒后才可再次发送")
	}
	times := dao.GetRedisCli().HGet(constant.CacheKeyVerifyCodeSendCountMap, key).Val()
	if convertutil.ParseInt(times) >= maxLimit {
		return result.Fail("今日验证码发送次数超过限制，请明日再尝试")
	}

	code := genutil.GenVerifyCode6Num()
	if tcentcloudutil.SendSmsVerifyCode(phone, code, ttl) {
		dao.GetRedisCli().Set(key, code, time.Duration(ttl)*time.Second)
		dao.GetRedisCli().HIncrBy(constant.CacheKeyVerifyCodeSendCountMap, key, 1)
		return result.Ok(ttl)
	}
	return result.Fail("验证码发送失败")
}
